const puppeteer = require("puppeteer-extra");
const StealthPlugin = require("puppeteer-extra-plugin-stealth");
puppeteer.use(StealthPlugin());
const userDataDir = process.env.WEB_CONFIG_USER_DATA_DIR;
const executablePath = process.env.WEB_CONFIG_EXECUTABLE_PATH;
const logger = require("../../utils/logger");
const notification = require("../../utils/notification");
const { sendWechatMessage } = require("../../utils");
const md5 = require("md5");
const axios = require("axios");
const dayjs = require("dayjs");
const fs = require("fs");
const path = require("path");
const { promisify } = require("util");
const stream = require("stream");
const pipeline = promisify(stream.pipeline);
// const { publishCallback } = require("../../utils");
const { saveMysql } = require("../../utils/saveMysql");
const { uploadVideoToQiniu } = require('../../config/qiniu')
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// 触发翻爬了
async function getUserInfo(keyword) {
  // if (!keyword) {
  //   throw new Error("KEYWORD_IS_REQURED");
  // }
  const browser = await puppeteer.launch({
    headless: "new",
    headless: false,
    userDataDir,
    executablePath,
    defaultViewport: null,
    args: [
      "--no-sandbox",
      "--disable-setuid-sandbox",
      "--disable-features=site-per-process",
      "--start-maximized",
      // "--auto-open-devtools-for-tabs",
    ],
    ignoreHTTPSErrors: true,
    // 忽略默认参数 --enable-automation, 防止被检测到是自动化测试
    ignoreDefaultArgs: ["--enable-automation"],
  });
  const page = await browser.newPage();
  // 设置 userAgent, 防止被检测到是自动化测试
  await page.setUserAgent(process.env.USER_AGENT);

  await page.goto(
    `https://www.xiaohongshu.com/search_result/?keyword=${keyword}&source=web_explore_feed&search_type=user&type=51`,
    {
      waitUntil: "domcontentloaded",
    }
  );
  // 等待页面元素加载完成
  await page.waitForSelector(".user");
  // 点击元素
  await page.click(".user");

}
async function getArticlesInfo(params) {
  const results = [];
  const browser = await puppeteer.launch({
    headless: "new",
    headless: false,
    userDataDir,
    executablePath,
    defaultViewport: null,
    args: [
      "--no-sandbox",
      "--disable-setuid-sandbox",
      "--disable-features=site-per-process",
      "--start-maximized",
    ],
    ignoreHTTPSErrors: true,
  });
  try {
    const page = await browser.newPage();
    await page.goto(`https://creator.xiaohongshu.com/creator/home`, {
      waitUntil: "networkidle0",
      timeout: 60000, // 增加超时时间到60秒
    });
    if (await isNotLogin(page)) {
      await notification(
        "小红书",
        `${process.env.NODE_ENV}环境下的小红书未登录`,
        "请扫码登录"
      );
      await page.evaluate(() => {
        const qrcodeButton = document.querySelector("img[class*='css-']");
        if (qrcodeButton) {
          qrcodeButton.click();
        }
      });
      await new Promise((resolve) => setTimeout(resolve, 3000));
      //获取页面所有的img，打印他们的宽高，找到第一个宽度大于100，小于 200的图片，返回它src
      let imgSrc = await page.evaluate(() => {
        const imgs = document.querySelectorAll("img");
        for (const img of imgs) {
          if (img.width > 100 && img.width < 200) {
            return img.src;
          }
        }
      });
      logger.info(`小红书登录二维码成功`);
      //获取base格式，发送微信消息
      const imgBase64 = imgSrc.split(",")[1];
      const imgBuffer = Buffer.from(imgSrc.split(",")[1], "base64");
      await sendWechatMessage({
        msgtype: "image",
        image: {
          base64: imgBase64,
          md5: md5(imgBuffer),
        },
      });
      logger.info("未登录，等待用户登录...");
      await waitForUserLogin(page);
      await notification(
        "小红书",
        `${process.env.NODE_ENV}环境下的小红书登录成功`,
        "登录成功"
      );
      logger.info("登录成功");
    }
    logger.info("已登录");
    const startDate = calculateStartDate(params);
    logger.info(`小红书，抓取开始时间: ${startDate}`);
    const endDate = dayjs(new Date().toString());
    logger.info(`小红书，抓取结束时间: ${endDate}`);
    //
    //拦截请求，修改参数
    const interceptPromise = new Promise((resolve, reject) => {
      page.on("request", async (interceptedRequest) => {
        const url = interceptedRequest.url();
        if (
          url.includes(
            "https://creator.xiaohongshu.com/api/galaxy/creator/note/user/posted"
          )
        ) {
          interceptedRequest.continue();
          const method = interceptedRequest.method();
          const headers = interceptedRequest.headers();
          const urlParams = new URLSearchParams(url.split("?")[1]);
          logger.info(`method: ${method}, urlParams: ${urlParams}`);
          const fans = await axios.get(
            "https://creator.xiaohongshu.com/api/galaxy/creator/data/fans/overall_new",
            {
              headers,
            }
          );
          logger.info(`粉丝数: ${fans.data.data.seven.fans_count}`);
          if (method === "GET" && urlParams) {
            try {
              let currentPage = 0;
              const maxPages = 100; // 设置最大页数限制
              let shouldContinue = true;

              while (currentPage < maxPages && shouldContinue) {
                const data = await getArticlesInfoByPage(
                  currentPage,
                  url,
                  method,
                  headers,
                  urlParams
                );
                for (const note of data.notes) {
                  const noteTime = dayjs(note.time);
                  logger.info(
                    `标题: ${note.display_title}, 发布时间: ${note.time
                    }, 是否置顶: ${note.sticky ? "是" : "否"}`
                  );
                  // 如果是置顶笔记，不考虑时间限制
                  if (!note.sticky && noteTime.isBefore(startDate)) {
                    shouldContinue = false;
                    break;
                  }
                  if (
                    note.sticky || // 置顶笔记始终包含
                    (noteTime.isAfter(startDate) &&
                      noteTime.isBefore(endDate)) ||
                    noteTime.isSame(endDate)
                  ) {
                    /**
                     *  title://标题
                     *  url://笔记链接
                     *  id://笔记id
                     *  cover://封面
                     *  publish_time://发布时间
                     *  read_count://浏览量
                     *  share_count://转发量
                     *  comment_count://评论量
                     *  like_count://点赞量
                     *  collect_count://收藏量
                     *  fans_count://粉丝量
                     */
                    results.push({
                      id: note.id,
                      title: note.display_title,
                      url: `https://www.xiaohongshu.com/explore/${note.id}?xsec_token=${note.xsec_token}&xsec_source=${note.xsec_source}`,
                      cover: JSON.stringify([note.images_list[0].url || ""]),
                      publish_time: dayjs(note.time).format(
                        "YYYY-MM-DD HH:mm:ss"
                      ),
                      read_count: note.view_count,
                      share_count: note.shared_count,
                      comment_count: note.comments_count,
                      like_count: note.likes,
                      collect_count: note.collected_count,
                      fans_count: fans.data.data.seven.fans_count,
                      is_sticky: note.sticky ? 1 : 0, // 添加是否置顶的标记
                    });
                  }
                }
                currentPage++;
                if (data.page === -1 || data.notes.length === 0) {
                  logger.info("没有更多数据了");
                  break;
                }
                if (!shouldContinue) {
                  logger.info("已达到开始时间，停止抓取");
                  break;
                }
                // 短暂的延迟，以避免请求过于频繁
                await new Promise((r) => setTimeout(r, 3000));
              }
              resolve();
            } catch (error) {
              logger.error(`获取文章信息时出错：${error.message}`);
              reject(error);
            }
          }
        } else {
          interceptedRequest.continue();
        }
      });
    });
    // 
    await page.setRequestInterception(true);
    // 等待元素出现
    await page.evaluate(() => {
      const link = Array.from(
        document.querySelectorAll("div[class*='menu-item'] span")
      ).find((span) => span.textContent.includes("笔记管理"));
      if (link) {
        link.click();
        console.log("通过 JavaScript 点击了 '笔记管理' 链接");
      } else {
        console.warn("在 JavaScript 中未找到 '笔记管理' 链接");
      }
    });
    // 再次等待导航完成
    await page.waitForNavigation({ waitUntil: "networkidle2" });
    try {
      await interceptPromise;

      return results;
    } catch (error) {
      logger.error(`拦截请求时发生错误: ${error.message}`);
      return [];
    }
  } catch (error) {
    logger.error(`发生错误: ${error.message}`);
    return [];
  } finally {
    await browser.close();
  }
}
// 判断是否需要登录
async function isNotLogin(page) {
  const loginButton = await page.$(".login-container");
  return loginButton;
}
//等待用户登录, 等待超过10分钟就抛出错误，结束定时器
async function waitForUserLogin(page) {
  return new Promise((resolve, reject) => {
    logger.info("请在浏览器中完成登录，登录成功后脚本将自动继续...");
    let qrCodeRefreshCount = 0;
    const maxRefreshAttempts = 5;
    const checkInterval = setInterval(async () => {
      try {
        const notLoggedIn = await isNotLogin(page);
        if (!notLoggedIn) {
          clearInterval(checkInterval);
          clearTimeout(timeoutId);
          logger.info("检测到登录成功");
          resolve();
        } else {
          // 检查二维码是否过期
          const isQRCodeExpired = await page.evaluate(() => {
            const expiredText = document.querySelector(".btn-content");
            return (
              expiredText &&
              !expiredText.parentElement.parentElement.style.display
            );
          });

          if (isQRCodeExpired && qrCodeRefreshCount < maxRefreshAttempts) {
            logger.info("二维码已过期，正在刷新...");
            await refreshQRCode(page);
            qrCodeRefreshCount++;
          }
        }
      } catch (error) {
        if (error.message.includes("Execution context was destroyed")) {
          logger.warn(
            "执行上下文被销毁，可能是由于导航导致的，忽略此错误并继续检查登录状态。"
          );
        } else {
          logger.error(`检查登录状态时出错:${error}`);
        }
      }
    }, 2000); // 每2秒检查一次

    // 设置10分钟超时
    const timeoutId = setTimeout(async () => {
      clearInterval(checkInterval);
      logger.error("登录等待超时（10分钟）");
      await notification(
        "小红书",
        `${process.env.NODE_ENV}环境下的小红书登录失败`,
        "等待超时"
      );
      reject(new Error("登录等待超时，请重试"));
    }, 10 * 60 * 1000); // 10分钟
  });
}
//分页请求
async function getArticlesInfoByPage(page, url, method, headers, params) {
  const response = await axios({
    url,
    method,
    headers,
    params: {
      ...params,
      page,
    },
  });
  logger.info(`小红书，正在请求第${page}页，url: ${url}, method: ${method}`);
  if (response.status >= 200 && response.status < 300) {
    if (response.data.result === 0) {
      logger.info(
        `小红书，请求第${page}页，url: ${url}, method: ${method}，成功`
      );
      return response.data.data;
    } else {
      throw new Error(`请求失败: ${response.data.message}`);
    }
  } else {
    throw new Error(`请求失败: ${response.statusText}`);
  }
}
//计算startDate
function calculateStartDate(params) {
  if (params.update_type === "highFrequency") {
    return dayjs().subtract(7, "day");
  } else if (params.interval) {
    const days = parseInt(params.interval);
    return dayjs().subtract(days, "day");
  } else {
    return dayjs("2024-01-01");
  }
}
//刷新二维码
async function refreshQRCode(page) {
  await page.evaluate(() => {
    const refreshButton = document.querySelector(".btn-content");
    if (refreshButton) {
      refreshButton.click();
    }
  });
  await notification(
    "小红书",
    `${process.env.NODE_ENV}环境下的小红书登录二维码已过期`,
    "正在刷新"
  );
  await new Promise((resolve) => setTimeout(resolve, 3000)); // 等待新二维码加载

  let imgSrc = await page.evaluate(() => {
    const imgs = document.querySelectorAll("img");
    for (const img of imgs) {
      if (img.width > 100 && img.width < 200) {
        return img.src;
      }
    }
  });

  logger.info(`小红书登录新二维码获取成功`);
  const imgBase64 = imgSrc.split(",")[1];
  const imgBuffer = Buffer.from(imgSrc.split(",")[1], "base64");

  await sendWechatMessage({
    msgtype: "image",
    image: {
      base64: imgBase64,
      md5: md5(imgBuffer),
    },
  });
}
//小红书发布
async function publish(params) {
  const browser = await puppeteer.launch({
    headless: false,
    userDataDir,
    executablePath,
    defaultViewport: null,
    args: [
      "--no-sandbox",
      "--disable-setuid-sandbox",
      "--disable-features=site-per-process",
      "--start-maximized",
      // "--auto-open-devtools-for-tabs",
      "--disable-notifications",
    ],
  });

  try {
    const page = await browser.newPage();
    await page.goto(`https://creator.xiaohongshu.com/creator/home`, {
      waitUntil: "networkidle0",
      timeout: 60000,
    });

    // 检查登录状态
    if (await isNotLogin(page)) {
      await handleLogin(page);
    }

    logger.info("已登录,准备发布文章");

    // 点击"发布笔记"按钮
    await page.evaluate(() => {
      const publishButton = Array.from(
        document.querySelectorAll("a[class*='btn']")
      ).find((el) => el.textContent.includes("发布笔记"));
      if (publishButton) publishButton.click();
    });
    // 判断是发布图文还是发布视频
    await handlePublishType(page, params);

    // 作者声明
    await handleAuthorStatement(page, params);

    // 可见范围
    await handleVisibleRange(page, params);
    await new Promise((resolve) => setTimeout(resolve, 3000));

    // 点击发布按钮
    const publishBtn = await page.waitForSelector(".publishBtn");
    if (publishBtn) publishBtn.click();
    // 监听页面响应 https://edith.xiaohongshu.com/web_api/sns/v2/note，如果成功说名发布成功
    const response = await page.waitForResponse(
      (response) =>
        response.request().method().toUpperCase() != "OPTIONS" &&
        response
          .url()
          .includes("https://edith.xiaohongshu.com/web_api/sns/v2/note")
    );
    if (response) {
      const responseData = await response.json();
      logger.info(`responseData: ${JSON.stringify(responseData)}`);
      if (responseData && responseData.success) {
        logger.info("文章发布成功");
        return {
          success: true,
          message: "文章发布成功",
          id: responseData.data.id,
        };
      } else {
        logger.error("文章发布失败");
        return {
          success: false,
          message: "文章发布失败",
        };
      }
    }
  } catch (error) {
    logger.error(`发布文章时发生错误: ${error.message}`);
    return { success: false, message: error.message };
  } finally {
    await browser.close();
  }
}

async function handleLogin(page) {
  await notification(
    "小红书",
    `${process.env.NODE_ENV}环境下的小红未登录`,
    "请扫码登录"
  );

  await page.evaluate(() => {
    const qrcodeButton = document.querySelector("img[class*='css-']");
    if (qrcodeButton) {
      qrcodeButton.click();
    }
  });
  await new Promise((resolve) => setTimeout(resolve, 3000));

  let imgSrc = await page.evaluate(() => {
    const imgs = document.querySelectorAll("img");
    for (const img of imgs) {
      if (img.width > 100 && img.width < 200) {
        return img.src;
      }
    }
  });

  logger.info(`小红书登录二维码成功`);
  const imgBase64 = imgSrc.split(",")[1];
  const imgBuffer = Buffer.from(imgSrc.split(",")[1], "base64");
  await sendWechatMessage({
    msgtype: "image",
    image: {
      base64: imgBase64,
      md5: md5(imgBuffer),
    },
  });

  logger.info("未登录，等待用户登录...");
  await waitForUserLogin(page);
  await notification(
    "小红书",
    `${process.env.NODE_ENV}环境下的小红书登录成功`,
    "登录成功"
  );
  logger.info("登录成功");
}
// 判断是发布图文还是发布视频
async function handlePublishType(page, params) {
  const publishType = params.content_type;
  logger.info(`发布类型: ${publishType}`);
  await page.waitForSelector(".creator-tab");
  try {
    if (publishType === "news") {
      // 点击图文发布标签
      await page.evaluate(() => {
        const tabs = document.querySelectorAll(".creator-tab");
        const newsTab = Array.from(tabs).find((tab) =>
          tab.textContent.includes("图文")
        );
        if (newsTab) newsTab.click();
        else throw new Error("未找到图文标签");
      });
      logger.info("已选择图文发布标签");
      // 下载所有图片
    } else if (publishType === "video") {
      // 点击视频发布标签
      await page.evaluate(() => {
        const tabs = document.querySelectorAll(".creator-tab");
        const videoTab = Array.from(tabs).find((tab) =>
          tab.textContent.includes("视频")
        );
        if (videoTab) videoTab.click();
        else throw new Error("未找到视频标签");
      });
      logger.info("已选择视频发布标签");
    } else {
      throw new Error(`不支持的发布类型: ${publishType}`);
    }
    // 下载文件
    await downloadFiles(params);
    // 上传文件
    await uploadFiles(page, params);
    await new Promise((resolve) => setTimeout(resolve, 2000));
    // 输入标题
    await page.waitForSelector(".titleInput input");
    await page.type(".titleInput input", params.title);
    logger.info(`标题: ${params.title}`);
    // 输入正文
    await page.waitForSelector('p[contenteditable="true"]');
    await page.type('p[contenteditable="true"]', params.summary);
    logger.info(`正文: ${params.summary}`);
    // 选择话题,
    if (params.talk && params.talk.length > 0) {
      for (const topic of params.talk) {
        await page.type('p[contenteditable="true"]', "#" + topic, {
          delay: 500,
        });
        await new Promise((resolve) => setTimeout(resolve, 1000));
        await page.evaluate(() => {
          const talks = document.querySelectorAll("li");
          const talk = Array.from(talks).find((t) =>
            t.classList.contains("publish-highlight")
          );
          console.log("first", talk);
          if (talk) {
            talk.click();
            talk.dispatchEvent(new Event("click", { bubbles: true }));
            talk.dispatchEvent(new Event("mousedown", { bubbles: true }));
          }
        });
        logger.info(`输入话题: ${topic}`);
        await new Promise((resolve) => setTimeout(resolve, 1000));
      }
    }
  } catch (error) {
    logger.error(`选择发布类型时出错: ${error.message}`);
    throw error;
  }
}
// 下载图片
async function downloadFiles(data) {
  logger.info(`开始下载文件，标题：${data.title}`);
  const date = dayjs().format("YYYY-MM-DD");
  const dir = path.join(__dirname, `../uploads/xiaohongshu/${date}`);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }

  const downloadPromises = [];

  // 处理视频
  if (data.video) {
    const videoName = path.basename(new URL(data.video).pathname);
    const videoPath = path.join(dir, videoName);
    downloadPromises.push(
      downloadFile(data.video, videoPath).then(() => {
        data.video = videoPath;
        logger.info(`视频下载成功，地址：${videoPath}`);
      })
    );
  }

  // 处理图片
  if (data.images) {
    const images = Array.isArray(data.images) ? data.images : [data.images];
    data.images = await Promise.all(
      images.map(async (imageUrl, index) => {
        const imageName = `image_${index}${path.extname(new URL(imageUrl).pathname) || ".jpg"
          }`;
        const imagePath = path.join(dir, imageName);
        await downloadFile(imageUrl, imagePath);
        logger.info(`图片下载成功，地址：${imagePath}`);
        return imagePath;
      })
    );
  }
  // 处理封面
  if (data.cover) {
    const coverName = path.basename(new URL(data.cover).pathname);
    const coverPath = path.join(dir, coverName);
    await downloadFile(data.cover, coverPath);
    data.cover = coverPath;
    logger.info(`封面下载成功，地址：${coverPath}`);
  }

  await Promise.all(downloadPromises);
  logger.info(`所有文件下载完成`);
}
// 上传文件
async function uploadFiles(page, params) {
  logger.info(`开始上传文件，标题：${params.title}`);

  try {
    if (
      params.content_type === "news" &&
      params.images &&
      params.images.length > 0
    ) {
      // 等待上传按钮出现
      await page.waitForSelector('input[type="file"]');

      // 获取文件上传输入元素
      const fileInput = await page.$('input[type="file"]');

      // 上传多张图片
      await fileInput.uploadFile(...params.images);

      // 使用 evaluateHandle 等待所有图片上传完成
      const imageContainersHandle = await page.evaluateHandle(
        (expectedCount) => {
          return new Promise((resolve) => {
            const checkImages = () => {
              const imageItems = document.querySelectorAll(".img-container");
              if (imageItems.length === expectedCount) {
                resolve(Array.from(imageItems));
              } else {
                setTimeout(checkImages, 500);
              }
            };
            checkImages();
          });
        },
        params.images.length
      );

      // 获取上传的图片数量
      const uploadedImagesCount = await page.evaluate(
        (handle) => handle.length,
        imageContainersHandle
      );

      logger.info(`成功上传 ${uploadedImagesCount} 张图片`);

      // 释放 handle
      await imageContainersHandle.dispose();
    } else if (params.content_type === "video" && params.video) {
      // 等待视频上传按钮出现
      await page.waitForSelector('input[type="file"]');

      // 获取视频上传输入元素
      const videoInput = await page.$('input[type="file"]');

      // 上传视频
      await videoInput.uploadFile(params.video);

      // 等待视频上传完成
      await page.waitForResponse(
        (response) =>
          response
            .url()
            .includes(
              "https://www.xiaohongshu.com/web_api/sns/v5/creator/file/encryption"
            ),
        { timeout: 60000 }
      );
      logger.info("视频上传成功");

      // 如果有封面图，上传封面图
      if (params.cover) {
        // 点击 修改封面
        await new Promise((resolve) => setTimeout(resolve, 2000));
        await page.evaluate(() => {
          const operators = document.querySelectorAll("div.operator span");
          const operator = Array.from(operators).find((op) =>
            op.textContent.includes("修改封面")
          );
          console.log("operator", operator);
          if (operator) {
            operator.click();
            operator.dispatchEvent(new Event("click", { bubbles: true }));
            operator.dispatchEvent(new Event("mousedown", { bubbles: true }));
          }
        });
        const tabUpload = await page.waitForSelector("#tab-uploadTab");
        if (tabUpload) {
          tabUpload.click();
        }
        // 等待封面上传按钮出现
        await page.waitForSelector('input[type="file"][accept*="image"]');

        // 获取封面上传输入元素
        const coverInput = await page.$('input[type="file"][accept*="image"]');

        // 上传封面
        await coverInput.uploadFile(params.cover);

        // 等待封面上传完成
        await page.waitForResponse((response) =>
          response.url().includes("blob:https://creator.xiaohongshu.com")
        );
        await new Promise((resolve) => setTimeout(resolve, 2000));
        // 点击确定
        await page.evaluate(() => {
          const confirmBtn = document.querySelector(".btn-confirm");
          if (confirmBtn) {
            confirmBtn.click();
          }
        });
        logger.info("封面上传成功");
      }
    }

    logger.info("所有文件上传完成");
  } catch (error) {
    logger.error(`上传文件时发生错误: ${error.message}`);
    throw error;
  }
}

async function downloadFile(fileUrl, localPath) {
  const response = await axios({
    method: "GET",
    url: fileUrl,
    responseType: "stream",
  });

  await pipeline(response.data, fs.createWriteStream(localPath));
}
// 作者声明
async function handleAuthorStatement(page, params) {
  //authorStatement: 0 虚构演绎，仅供娱乐 1 笔记含AI合成内容 2 已自主标注 3 自主拍摄 4 来源转载
  const authorStatement = params.author_statement;
  const declarationWrapper = await page.$(".declaration-wrapper");
  if (declarationWrapper) {
    declarationWrapper.click();
    await new Promise((resolve) => setTimeout(resolve, 1500));
    await page.evaluate(() => {
      const elPoppers = document.querySelectorAll(".el-popper");
      Array.from(elPoppers).forEach((el) => {
        const spans = el.querySelectorAll("span");
        const span = Array.from(spans).find((s) =>
          s.textContent.includes("内容来源声明")
        );
        if (span) {
          span.click();
        }
      });
    });
    await new Promise((resolve) => setTimeout(resolve, 1500));
    if (authorStatement == 0) {
      await page.evaluate(() => {
        const elPoppers = document.querySelectorAll(".el-popper");
        Array.from(elPoppers).forEach((el) => {
          const spans = el.querySelectorAll("span");
          const span = Array.from(spans).find((s) =>
            s.textContent.includes("虚构演绎，仅供娱乐")
          );
          if (span) {
            span.click();
          }
        });
      });
    } else if (authorStatement == 1) {
      await page.evaluate(() => {
        const elPoppers = document.querySelectorAll(".el-popper");
        Array.from(elPoppers).forEach((el) => {
          const spans = el.querySelectorAll("span");
          const span = Array.from(spans).find((s) =>
            s.textContent.includes("笔记含AI合成内容")
          );
          if (span) {
            span.click();
          }
        });
      });
    } else if (authorStatement == 2) {
      await new Promise((resolve) => setTimeout(resolve, 1500));
      await page.evaluate(() => {
        const elPoppers = document.querySelectorAll(".el-popper");
        Array.from(elPoppers).forEach((el) => {
          const spans = el.querySelectorAll("span");
          const span = Array.from(spans).find((s) =>
            s.textContent.includes("已自主标注")
          );
          if (span) {
            span.click();
          }
        });
      });
    } else if (authorStatement == 3) {
      await new Promise((resolve) => setTimeout(resolve, 1500));
      await page.evaluate(() => {
        const elPoppers = document.querySelectorAll(".el-popper");
        Array.from(elPoppers).forEach((el) => {
          const spans = el.querySelectorAll("span");
          const span = Array.from(spans).find((s) =>
            s.textContent.includes("自主拍摄")
          );
          if (span) {
            span.click();
          }
        });
      });
      const coloseIcon = await page.$(".el-dialog__close");
      if (coloseIcon) {
        coloseIcon.click();
      }
    } else if (authorStatement == 4) {
      await new Promise((resolve) => setTimeout(resolve, 1500));
      await page.evaluate(() => {
        const elPoppers = document.querySelectorAll(".el-popper");
        Array.from(elPoppers).forEach((el) => {
          const spans = el.querySelectorAll("span");
          const span = Array.from(spans).find((s) =>
            s.textContent.includes("来源转载")
          );
          if (span) {
            span.click();
          }
        });
      });
      const coloseIcon = await page.$(".el-dialog__close");
      if (coloseIcon) {
        coloseIcon.click();
      }
    }
  }
}
// 可见范围
async function handleVisibleRange(page, params) {
  let permissionObj = {
    1: "公开",
    2: "私密",
  };
  let permission = params.permission;
  await page.evaluate(
    (permission, permissionObj) => {
      const elRadio = document.querySelectorAll("label.el-radio");
      const elRadioItem = Array.from(elRadio).find((el) =>
        el.textContent.includes(permissionObj[permission])
      );
      if (elRadioItem) {
        elRadioItem.click();
      }
    },
    permission,
    permissionObj
  );
}

// 更新handleCommand函数
exports.handleCommand = async (command, params, taskId) => {
  switch (command) {

    case "getUserInfo":
      try {
        const user = await getUserInfo(params?.keyword);
        console.log('------>小红书用户信息:', user)
        return user;
      } catch (error) {
        throw error;
      }
    case "getArticlesInfo":
      const data = await getArticlesInfo(params);
      console.log('------>小红书抓取data:', data)
      if (data.length > 0) {
        //保存数据库
        await saveXiaohongshu2Info(data);
      }
      return { data };
    case "publish":
      try {
        const result = await publish(params);
        if (result.success) {
          // await publishCallback(
          //   params.post_id,
          //   3,
          //   "发布成功",
          //   taskId,
          //   result.id
          // );
          return {
            data: [
              {
                ...result,
              },
            ],
          };
        } else {
          throw new Error(result.message);
        }
      } catch (error) {
        logger.error(`发布文章时发生错误: ${error.message}`);
        // await publishCallback(params.post_id, 4, error.message, taskId, "");
        return {
          data: [
            {
              success: false,
              message: error.message,
            },
          ],
        };
      }
    default:
      throw new Error("NOT_SUPPORT_COMMAND");
  }
};


const saveXiaohongshu2Info = async (data) => {
  try {
    for (const item of data) {
      // 视频上传七牛云
      // const video_url = await uploadVideoToQiniu(item.url, 'xiaohongshu');
      // console.log('------>小红书视频:', video_url)
      // 封面上传七牛云

      // const cover_url = await uploadVideoToQiniu(item.cover, 'xiaohongshu');
      // console.log('------>小红书封面:', cover_url)

      const saveData = {
        // 平台标识，固定为"xiaohongshu"
        platform: "xiaohongshu",
        // 视频唯一标识ID (这里用文章ID代替)
        aweme_id: item.id, // Using item ID as aweme_id
        // 视频创建时间 (这里用文章发布时间代替)
        create_time: dayjs(item.publish_time).unix(), // Using publish_time as create_time
        // 数据爬取时间，格式：YYYY-MM-DD HH:mm:ss
        crawl_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),

        // 作者UID，用户的唯一数字标识 (假设有类似字段)
        author_uid: '', // Placeholder, adjust as needed
        // 作者加密ID (假设有类似字段)
        author_sec_uid: '', // Placeholder, adjust as needed
        // 作者昵称 (假设有类似字段)
        author_nickname: '', // Placeholder, adjust as needed
        // 作者个人签名 (假设有类似字段)
        author_signature: '', // Placeholder, adjust as needed
        // 作者头像URL (假设有类似字段)
        author_avatar_url: '', // Placeholder, adjust as needed
        // 作者关注数量 (假设有类似字段)
        author_following_count: 0, // Placeholder, adjust as needed
        // 作者粉丝数量
        author_follower_count: item.fans_count, // Using fans_count
        // 作者获赞总数 (假设有类似字段)
        author_total_favorited: 0, // Placeholder, adjust as needed
        // 作者抖音号 (假设有类似字段)
        author_unique_id: '', // Placeholder, adjust as needed

        // 视频描述/标题 (这里用文章标题代替)
        video_desc: item.title, // Using title as video_desc
        // 视频播放地址 (这里用文章URL代替)
        video_url: item.url, // Using URL as video_url
        // 视频封面图片地址
        cover_url: item.cover, // Assuming cover is a JSON string of an array
        // 视频时长（毫秒） (假设有类似字段)
        duration: 0, // Placeholder, adjust as needed
        // 视频宽度（像素） (假设有类似字段)
        width: 0, // Placeholder, adjust as needed
        // 视频高度（像素） (假设有类似字段)
        height: 0, // Placeholder, adjust as needed

        // 评论数量
        comment_count: item.comment_count,
        // 点赞数量
        digg_count: item.like_count, // Assuming like_count maps to digg_count
        // 下载数量 (假设有类似字段)
        download_count: 0, // Placeholder, adjust as needed
        // 转发数量 (假设有类似字段)
        forward_count: 0, // Placeholder, adjust as needed
        // 播放数量 (假设有类似字段)
        play_count: item.read_count, // Assuming read_count maps to play_count
        // 分享数量
        share_count: item.share_count,

        // 背景音乐ID (假设有类似字段)
        music_id: '', // Placeholder, adjust as needed
        // 背景音乐标题 (假设有类似字段)
        music_title: '', // Placeholder, adjust as needed
        // 背景音乐作者 (假设有类似字段)
        music_author: '', // Placeholder, adjust as needed
        // 背景音乐时长 (假设有类似字段)
        music_duration: 0, // Placeholder, adjust as needed

        // 视频包含的话题标签，JSON字符串格式
        // 包含话题名称(hashtag_name)和话题ID(hashtag_id)
        hashtags: JSON.stringify([]) // Assuming no hashtags provided
      };

      // 使用保存函数
      await saveMysql(saveData);
      // 添加延迟避免请求过快
      await delay(1000);
    }
    logger.info(`数据保存完成，共处理 ${data.length} 条记录`);
  } catch (error) {
    logger.error(`保存小红书数据时发生错误: ${error.message}`);
    throw error;
  }
}



